dataKey = 'login_taobao_com'
loginInfo = {}

#保存界面数据
saveUserData = ->
	obj = {}
	obj[dataKey] = $('form').serializeObject()
	chrome.storage.local.set obj
#编辑模式
editModel = ->
	$('table').addClass('editModel')
	$('input').removeAttr('readonly')
#设置拼音
setPy = (save=off)->
	cnt = 0
	$('[name="username[]"]').each ->
		that = this
		if this.value
			cnt++
			$.getJSON 'http://huoqu.sinaapp.com/pinyin/',m:'JSON',a:this.value,(data)->
				pyEle = $(that).next()
				if data?.all
					thisPy = data.all.toLowerCase() 
					if pyEle.val() != thisPy
						pyEle.val thisPy
				if save and !--cnt
					saveUserData()
#得到一行用户名和密码
getTrHtml = (name='',password='',py="",show=on)->
	className =''
	className = 'hide' unless show
	usernameTitle = ''
	if py
		usernameTitle = "拼音：#{py}"
	"""
		<tr class="#{className}">
			<td>
				<input name="username[]" title="#{usernameTitle}" type="text" value="#{htmlEncode(name)}" placeholder="输入旺旺用户名" readonly="readonly" />
				<input name="userPY[]" type="hidden" value="#{htmlEncode(py)}" />
			</td>
			<td class="passCol">
				<input name="password[]" type="password" value="#{htmlEncode(password)}" placeholder="输入旺旺密码" />
			</td>
			<td>
				<button class="btn loginAction btn-primary" type="button">登录</button>
			</td>
		</tr>
	"""
	#只返回一个字符串
	
#展示界面数据
showUserData = (search='',callback='')->
	search = search.replace(/[.{}| $^*+?\[\]]/g ,'')
	if search
		sep = '.*'
		search = search.split('')
		search = search.join(sep)
		search = search.toLowerCase()
		search = new RegExp(search)
	chrome.storage.local.get dataKey,(item)->
		obj=
			username:['']
			password:['']
		if item and item[dataKey]
			obj=item[dataKey]
		tbody=''
		if obj.username
			for v,i in obj.username
				if !v
					continue
				tbody += getTrHtml v,obj.password[i],obj.userPY[i],!search or search.test(v.toLowerCase()) or search.test(obj.userPY[i])
		unless tbody
			tbody += getTrHtml()
		$('tbody').html tbody
		if $.isFunction callback
			callback()
showUserData()
#绑定事件
$('#save').click ->
	saveUserData()
	setPy on
$('#addLine').click ->
	newLine =$(getTrHtml())
	$('tbody').append newLine
	editModel()
	newLine.find('[name="username[]"]').focus()
$('#edit').click editModel
$('.loginAction').live('click',->
	saveUserData()
	setPy on
	$tr = $(this).closest('tr')
	usernameEle = $('[name="username[]"]',$tr)
	username = usernameEle.val()
	passwordEle = $('[name="password[]"]',$tr)
	password = passwordEle.val()
	unless username
		alert '请输入用户名'
		usernameEle.focus()
		return false
	unless password
		alert '请认输密码'
		passwordEle.focus()
		return off
	loginInfo =
		username:username
		password:password
	delCook()
	noProxy()
	chrome.extension.getBackgroundPage().msg 'loginInfo',loginInfo
	setTimeout( ->
		open 'http://trade.taobao.com/trade/itemlist/list_bought_items.htm'
	,900)
)
$usernameInput = $('[name="username[]"]').live 'keyup',->
	[username,password] = this.value.split("\t")
	if password
		this.value = username
		$(this).closest('tr').find('[name="password[]"]').val password
$usernameInput.live 'blur', ->
	this.value = this.value.trim()
$('#search').focus().keyup (e)->
	showUserData this.value,->
		btn = $('tbody tr td button:visible')
		help = $('.help-block')
		if 1==btn.size()
			help.text("回车直接使用“#{$('[name*=username]',btn.closest('tr')).val()}”登录").removeClass('hide')
		else
			help.addClass('hide')

	btn = $('tbody tr td button:visible')
	if 13 == e.keyCode
		if 1==btn.size()
			btn.click()
